from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from ..models import Appointment, VaccinationSite, User, db
from datetime import datetime
import random
import string

appointment_bp = Blueprint('appointment', __name__)

def generate_appointment_no():
    """生成预约号: AP + 年月日 + 4位随机数"""
    date_str = datetime.now().strftime('%Y%m%d')
    random_str = ''.join(random.choices(string.digits, k=4))
    return f'AP{date_str}{random_str}'

@appointment_bp.route('/create', methods=['POST'])
@jwt_required()
def create_appointment():
    try:
        data = request.get_json()
        print("接收到的数据:", data)
        user_id = get_jwt_identity()
        
        # 从 Proxy 对象中提取实际数据
        site_data = dict(data['site'])
        vaccine_data = dict(data['vaccine'])
        time_data = dict(data['time'])
        
        # 验证接种点是否存在且可预约
        site = VaccinationSite.query.get(site_data['id'])
        if not site:
            return jsonify({
                'code': 404,
                'msg': '接种点不存在'
            }), 404
        if site.status != '可预约':
            return jsonify({
                'code': 400,
                'msg': '该接种点暂不可预约'
            }), 400
        
        # 验证疫苗数量是否充足
        if site.vaccineCount <= 0:
            return jsonify({
                'code': 400,
                'msg': '疫苗库存不足'
            }), 400
        
        try:
            # 生成预约号
            appointment_no = generate_appointment_no()
            
            # 创建预约
            appointment = Appointment(
                appointment_no=appointment_no,
                user_id=user_id,
                site_id=site.id,
                vaccine_name=vaccine_data['name'],
                appointment_date=datetime.strptime(data['date'], '%Y-%m-%d').date(),
                appointment_time=time_data['time'],
                status='待接种'  # 修改初始状态
            )
            
            # 更新疫苗数量
            site.vaccineCount -= 1
            if site.vaccineCount <= 0:
                site.status = '已约满'
            
            db.session.add(appointment)
            db.session.commit()
            
            return jsonify({
                'code': 200,
                'msg': '预约成功',
                'data': {
                    'id': appointment.id,
                    'appointment_no': appointment.appointment_no,
                    'date': data['date'],
                    'time': time_data['time'],
                    'site': {
                        'name': site.name,
                        'address': site.address
                    },
                    'vaccine': {
                        'name': vaccine_data['name'],
                        'manufacturer': vaccine_data['manufacturer']
                    },
                    'status': appointment.status
                }
            }), 200
            
        except Exception as e:
            print("错误信息:", str(e))
            db.session.rollback()
            return jsonify({
                'code': 500,
                'msg': f'服务器错误: {str(e)}',
                'data': None
            }), 500
    except Exception as e:
        print("错误信息:", str(e))
        return jsonify({
            'code': 500,
            'msg': f'服务器错误: {str(e)}',
            'data': None
        }), 500

@appointment_bp.route('/my', methods=['GET'])
@jwt_required()
def get_my_appointments():
    """获取我的预约列表"""
    user_id = get_jwt_identity()
    
    appointments = Appointment.query.filter_by(user_id=user_id).order_by(Appointment.created_at.desc()).all()
    
    return jsonify({
        'code': 200,
        'msg': '获取成功',
        'data': [{
            'id': apt.id,
            'appointment_no': apt.appointment_no,
            'date': apt.appointment_date.strftime('%Y-%m-%d'),
            'time': apt.appointment_time,
            'site': {
                'name': apt.site.name,
                'address': apt.site.address
            },
            'vaccine': {
                'name': apt.vaccine_name
            },
            'status': apt.status
        } for apt in appointments]
    }), 200

@appointment_bp.route('/cancel/<int:id>', methods=['POST'])
@jwt_required()
def cancel_appointment(id):
    """取消预约"""
    user_id = get_jwt_identity()
    
    appointment = Appointment.query.filter_by(id=id, user_id=user_id).first()
    if not appointment:
        return jsonify({
            'code': 404,
            'msg': '预约不存在'
        }), 404
        
    if appointment.status != '待接种':
        return jsonify({
            'code': 400,
            'msg': '该预约无法取消'
        }), 400
    
    try:
        # 更新预约状态
        appointment.status = '已取消'
        
        # 恢复接种点疫苗数量
        site = appointment.site
        site.vaccineCount += 1
        if site.status == '已约满':
            site.status = '可预约'
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'msg': '取消预约成功',
            'data': None
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'code': 500,
            'msg': '服务器错误',
            'data': None
        }), 500 